
class Util:

    # 单一职责原则：一个方法只完成一个功能
    @classmethod
    def incrypt_md5(cls, msg):
        """
        将传递的明文字符串通过MD5方式加密为密文字符串
        :param msg: 明文字符串
        :return: 密文字符串
        """
        import hashlib
        md5 = hashlib.md5()
        md5.update(msg.encode())
        return md5.hexdigest()

    @classmethod
    def get_mysql_conn(cls):
        import pymysql
        return pymysql.connect('192.168.221.128', 'root', '123456', 'sales')

    @classmethod
    def update(cls, sql):
        # 增删改操作
        # 对于资源，基本的原则是先开的后关
        conn = cls.get_mysql_conn()
        cur = conn.cursor()
        cur.execute(sql)
        conn.commit()
        cur.close()
        conn.close()

    @classmethod
    def query(cls, sql):
        conn = cls.get_mysql_conn()
        cur = conn.cursor()
        cur.execute(sql)
        result = cur.fetchall()  # 返回二维元组
        cur.close()
        conn.close()
        return result

    @classmethod
    def get_redis_conn(cls):
        import redis
        pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True, db=0)
        return redis.Redis(connection_pool=pool)

    @classmethod
    def get_vfcode(cls):
        import random
        """
        生成4位随机数字或字母（大写）组成的验证码并返回
        :return:
        """
        li = []  # 存放所有可能的数据
        for i in range(10):
            li.append(str(i))

        for j in range(ord('A'), ord('Z')+1):
            li.append(chr(j))

        vfcode = ''
        for k in range(4):
            random_index = random.randint(0,len(li)-1)
            vfcode += li[random_index]
        return vfcode


if __name__ == '__main__':

    # print(Util.get_mysql_conn())
    # sql1  = 'insert into goods(gname,price,store) values("皮鞋", 300, 20)'
    # Util.update(sql1)
    # sql2  = 'select gname, price from goods where gid=1'
    # print(Util.query(sql2))
    Util.get_vfcode()
